import "dart:ffi";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/add_apartment/sectinos/floors.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/select_building.dart";
import "package:ct_pa_majordomo/pages/main.dart";
import "package:ct_pa_majordomo/pages/widgets/form_select_field.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/wrap_item.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:flutter_form_builder/flutter_form_builder.dart";

class AddFloor extends StatefulWidget {
  const AddFloor({super.key});

  @override
  State<StatefulWidget> createState() => _AddFloorState();

}

class _AddFloorState extends State<AddFloor> {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();
  final List<int> _numList = List.generate(99, (index) => index + 1);
  List<int?> _floorNumList = List.generate(99, (index) => index + 1);

  final Text _required = const Text("*", style: TextStyle(color: ThemeVars.colorError));

  List<Map> _floorData = [];
  int _buildingId = -1;
  String _buildingName = "";
  List _buildingList = [];

  FormBuilderState get _formState => _formKey.currentState!;

  Map<String, FormBuilderFieldState> get _fields => _formState.fields;

  Map<String, dynamic> get _instantValue => _formState.instantValue;


  Future<void> _changeNum(String field) async {
    int? popped;
    if (field != "roomPrefix") {
      int? value = _fields[field]?.value;
      popped = await showRoundedBottomSheet(
        builder: (context) => BottomSheetSelect(
          items: field == "floors" ? _floorNumList : _numList,
          compare: (item) => item == value,
        ),
      );
    }


    if (popped != null) {
      _fields[field]?.didChange(popped);
    }
    _valueChange();
  }

  void _valueChange() {
    int floors = _instantValue["floors"];
    int rooms = _instantValue["rooms"];
    // String roomPrefix = _fields[field]?.value;
    setState(() {
      List<String> roomNameList = [];
      for (int i = 1; i <= rooms; i++) {
        roomNameList.add("${_instantValue["roomPrefix"] ?? ''}$floors${i < 10 ? "0$i" : i}");
      }
      _floorData = [{"floor": floors, "room": rooms, "roomNameList": roomNameList}];
    });
  }

  bool _valid() {
    return _instantValue["floors"] != null
        && _instantValue["rooms"] != null
        && Utils.isNotEmpty(_instantValue["buildingId"]);
  }

  /* 获取楼栋列表 */
  Future<void> _getBuildingList() async {
    List resData = await apartmentApi.getBuildingList();
    setState(() {
      _buildingList = resData;
    });
  }

  void _refreshFloors(id) {
    Map building = _buildingList.firstWhere((item) => item["buildingId"] == id);
    List floors = building["floorList"].map((item) => int.parse(item["floorName"])).toList();
    print(floors);
    setState(() {
      _floorNumList = [];
      for (int item in _numList) {
        print(floors.contains(item));
        if (!floors.contains(item)) {
          _floorNumList.add(item);
        }
      }
      _fields["floors"]?.didChange(_floorNumList[0]);
      _valueChange();
    });
  }

  void _createBuilding(Map params) async {
    await apartmentApi.createBuilding(params);
    EasyLoading.showToast("添加成功");
    Stacker.pushAndRemoveUntil(const Main(index: 1,));
  }

  @override
  void initState() {
    _getBuildingList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "添加整层",
      child: Stack(
        children: [
          ListView(
            children: [
              FormBuilder(
                key: _formKey,
                child: MenuBlock(
                    borderRadius: BorderRadius.zero,
                    items: [
                      MenuBlockItem(
                        text: "选择公寓",
                        prefix: _required,
                        suffix: const FormSelectField(name: "buildingId"),
                        onTap: () {
                          showSelectBuilding(
                            context: context,
                            buildingId: _buildingId,
                            list: _buildingList,
                            statusBarHeight: MediaQuery.of(context).padding.top,
                            onChange: (id, name) => setState(() {
                              _buildingId = id;
                              _buildingName = name;
                              _fields["buildingId"]?.didChange(name);
                              _refreshFloors(id);
                            })
                          );
                        },
                      ),
                      MenuBlockItem(
                        text: "选择层数",
                        prefix: _required,
                        suffix: const FormSelectField(name: "floors"),
                        onTap: () => _changeNum("floors"),
                      ),
                      MenuBlockItem(
                        prefix: _required,
                        text: "每层房间数",
                        suffix: const FormSelectField(initialValue: 1, name: "rooms"),
                        onTap: () => _changeNum("rooms"),
                      ),
                      MenuBlockItem(
                        text: "房间号加前缀",
                        suffix: FormBuilderTextField(
                          decoration: const InputDecoration(
                            counterText: "",
                            hintText: "请输入1位数字/字母",
                          ),
                          inputFormatters: [
                            FilteringTextInputFormatter.allow(RegExp(r"[a-zA-Z1-9]")),
                          ],
                          maxLength: 1,
                          textAlign: TextAlign.right,
                          name: "roomPrefix",
                          onChanged: (value) => _changeNum("roomPrefix"),
                        ),
                      ),
                    ]
                ),
              ),
              const SizedBox(height: 15),
              if (_floorData.isNotEmpty && _floorData[0]["roomNameList"] != null) Container(
                width: MediaQuery.of(context).size.width,
                padding: const EdgeInsets.all(ThemeVars.paddingPage),
                decoration: const BoxDecoration(
                    color: ThemeVars.colorBackground
                ),
                child: Wrap(
                  spacing: 12,
                  runSpacing: 12,
                  children: List.generate(_floorData[0]["roomNameList"].length, (index) {
                    return WrapItem(
                        span: 3,
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 6),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: const BorderRadius.all(Radius.circular(5)),
                              border: Border.all(color: ThemeVars.colorPrimary)
                          ),
                          child: Text(_floorData[0]["roomNameList"][index], style: const TextStyle(color: ThemeVars.colorPrimary),),
                        )
                    );
                  }),
                ),
              ),
            ],
          ),
          Positioned(
            bottom: 0,
            left: 0,
            width: MediaQuery.of(context).size.width,
            child: Container(
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              decoration: const BoxDecoration(
                color: ThemeVars.colorBackground,
              ),
              child: Button(
                  type: ButtonType.primary,
                  onPressed: () {
                    if (_valid()) {
                      Map params = {
                        "floors": _floorData,
                        "buildingId": _buildingId
                      };
                      print(params);
                      _createBuilding(params);
                    }
                  },
                  child: const Text("下一步")
              ),
            )
          ),
        ],
      ),
    );
  }

}